package repository

import (
	"errors"

	"away.wei/minidevpos/db"
	"away.wei/minidevpos/global"
	"away.wei/minidevpos/model"
	"gorm.io/gorm"
)

type ServerRep struct{}

func (s *ServerRep) Create(dto db.Server) error {
	if (!errors.Is(global.DB.First(&db.Server{}, "ip = ?", dto.IP).Error, gorm.ErrRecordNotFound)) {
		return errors.New("存在相同的ip，不允许创建")
	}
	return global.DB.Create(&dto).Error
}

func (s *ServerRep) Delete(ids []int) error {
	return global.DB.Delete(&db.Server{}, "id in ?", ids).Error
}

func (s *ServerRep) Update(dto db.Server) error {
	return global.DB.Updates(&dto).Error
}

func (s *ServerRep) GetPage(dto model.ServerSearch) (list []db.Server, total int64, err error) {
	limit := dto.PageSize
	offset := dto.PageSize * (dto.Page - 1)
	dbquery := global.DB.Model(&db.Server{})

	err = dbquery.Count(&total).Error
	if err != nil {
		return
	}
	if dto.IP != "" {
		dbquery = dbquery.Where("ip like ?", "%"+dto.IP+"%")
	}
	err = dbquery.Limit(limit).Offset(offset).Find(&list).Error
	return list, total, err
}

func (s *ServerRep) GetAll() (list []db.Server, err error) {
	err = global.DB.Model(&db.Server{}).Find(&list).Error
	return list, err
}

func (s *ServerRep) GetIds(dto model.IdsReq) (list []db.Server, err error) {
	err = global.DB.Model(&db.Server{}).Find(&list, "id in ?", dto.Ids).Error
	return list, err
}
